package integermap.service;

import java.util.*;

/**
 * @author alex
 */
public class DataGenerator {
    /**
     * Generates a list of integers with provided rate of hash collisions
     * @param elementsCount the count of elements
     * @param collisionsRate the collisions rate
     * @return the integers list
     */
    public static List<Integer> generate(int elementsCount, float collisionsRate) {
        Random random = new Random();

        int collisionsMax = (int) (elementsCount * collisionsRate);
        int collisionsCount = 0;
        int element, hash;

        List<Integer> elements = new ArrayList<>();
        Set<Integer> hashes = new HashSet<>();

        while (elements.size() < elementsCount) {
            element = random.nextInt();
            if (element == Integer.MIN_VALUE)
                continue;
            hash = hash(element, elementsCount);

            if (hashes.contains(hash)) {
                if (collisionsCount < collisionsMax)
                    collisionsCount++;
                else
                    continue;
            }

            elements.add(element);
            hashes.add(hash);
        }

        return elements;
    }

    /**
     * The hash function
     * @param element the current element
     * @param elementsCount the count of elements
     * @return the hash
     */
    private static int hash(int element, int elementsCount) {
        return Math.abs(element % elementsCount);
    }
}
